package
{
	import com.doucome.snapshot.Global;
	import com.doucome.snapshot.User;
	import com.doucome.snapshot.view.BG;
	import com.doucome.snapshot.view.BtnStart;
	import com.doucome.snapshot.view.IndexView;
	import com.doucome.snapshot.view.LinkView;
	import com.doucome.snapshot.view.MCamera;
	import com.doucome.snapshot.view.UploadView;
	import com.doucome.snapshot.view.WaitEffect;
	import com.doucome.snapshot.view.WindowError;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.system.Security;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	/**
	 * ...
	 * @author wkl
	 */
	public class Main extends Sprite
	{
		
		private var _link_view:LinkView;
		private var _camera_view:Sprite;
		private var _mcamera:MCamera;
		private var _index_view:IndexView;
		private var _upload_view:UploadView;
		private var _bg:BG;
		private var _welcome_txt:TextField;
		var _btn_start:BtnStart;
		private var host:String;
		//user info
		private var user:User;
		private var _window_error:WindowError;
		private var _waitEffect:WaitEffect
		private var source_type:int; //快照来源
		private var edit_status:Boolean = false; //是否修改状态
		public static const PIC_SOURCE_CAMERA = 1;
		public static const PIC_SOURCE_UPLOAD = 2;
		
		public function Main():void
		{
			if (stage)
				init();
			else
				addEventListener(Event.ADDED_TO_STAGE, init);
		
		}
		
		private function init(e:Event = null):void
		{
			Security.allowDomain("*");
			Security.allowInsecureDomain("*");
			apicheck();
			
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			trace("dau>100000");
			//init
			//读取参数
			
			//load parameters
			user = new User();
			var userid = this.stage.loaderInfo.parameters.userid;
			user.id = userid;
			user.nickname = this.stage.loaderInfo.parameters.nickname;
			user.gender = this.stage.loaderInfo.parameters.gender;
			user.province = this.stage.loaderInfo.parameters.province;
			user.country = this.stage.loaderInfo.parameters.country;
			user.city = this.stage.loaderInfo.parameters.city;
			user.figureurl = this.stage.loaderInfo.parameters.figureurl;
			//get sever info
			var app_server = this.stage.loaderInfo.parameters.appserver;
			var img_server = this.stage.loaderInfo.parameters.imgserver;
			//saved in Global
			
			//调试用
			//trace(user);
			if (app_server == undefined)
			{
				app_server = "dev.doucome.com";
			}
			
			if (img_server == undefined)
			{
				img_server = "dev.doucome.com";
			}
			
			if (userid == undefined)
			{
				user.id = 0;
				user.nickname = "corner";
				user.gender = "女";
				user.province = "浙江";
				user.city = "杭州";
				user.figureurl = "http://thirdapp0.qlogo.cn/qzopenapp/d8219673598dbd6f7bab6efcc1705ca216b06f8c6f8dea7a9875285503236f39/30";
			}
			
			//初始化背景
			_bg = new BG(user);
			addChild(_bg);
			
			//初始化相机界面
			_camera_view = new Sprite();
			
			//初始化Link界面
			_link_view = new LinkView();
			
			//upload
			_upload_view = new UploadView;
			
			//错误提示窗
			_window_error = new WindowError();
			_window_error.visible = false;
			addChild(_window_error);
			
			//保存全局变量
			Global.user = user;
			Global.APP_SERVER = app_server;
			Global.IMG_SERVER = img_server;
			Global.bg = _bg;
			
			//默认启动摄像头
			source_type = PIC_SOURCE_CAMERA;
			
			initIndexView();
		
		}
		
		//外部api注册检测
		public function apicheck():void
		{
			if (ExternalInterface.available)
			{
				try
				{
					var containerReady:Boolean = isContainerReady();
					if (containerReady)
					{
						// If the container is ready, register the SWF's functions. 
						setupCallbacks();
					}
					else
					{
						var readyTimer:Timer = new Timer(100);
						readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
						readyTimer.start();
					}
				}
				catch (ex)
				{
					
				}
			}
		}
		
		private function isContainerReady():Boolean
		{
			var result:Boolean = ExternalInterface.call("isReady");
			return result;
		}
		
		private function timerHandler(event:TimerEvent):void
		{
			// Check if the container is now ready. 
			var isReady:Boolean = isContainerReady();
			if (isReady)
			{
				Timer(event.target).stop();
				setupCallbacks();
			}
		}
		
		//js函数调用注册
		private function setupCallbacks():void
		{
			ExternalInterface.addCallback("sync", js_sync);
		}
		
		//js外部调用，同步数据
		public function js_sync():void
		{
			_bg.sync();
		}
		
		//index界面
		private function initIndexView():void
		{
			
			_index_view = new IndexView();
			_index_view.x = 378;
			_index_view.y = 288.95;
			addChild(_index_view);
			_btn_start = new BtnStart();
			_btn_start.x = 588;
			_btn_start.y = 497;
			_btn_start.addEventListener(MouseEvent.CLICK, onStart);
			_index_view.addEventListener(IndexView.INDEX_START_EVENT, onIndexStart);
			addChild(_btn_start);
			_btn_start.visible = false;
		
		}
		
		private function onIndexStart(e:Event):void
		{
			_btn_start.visible = true;
		}
		
		private function onStart(e:Event):void
		{
			
			//_wait_effect
			_waitEffect = new WaitEffect;
			addChild(_waitEffect);
			_waitEffect.show();
			
			if (contains(_index_view))
			{
				removeChild(_index_view);
			}
			if (contains(_btn_start))
			{
				removeChild(_btn_start);
			}
			
			//同步数据
			_bg.addEventListener(BG.SYNC_COMPLETE_EVENT, onSyncComplete);
			_bg.sync();
		
		}
		
		private function onSyncComplete(e:Event):void
		{
			_waitEffect.close();
			
			switch (source_type)
			{
				
				case PIC_SOURCE_CAMERA:
					
					//初始化相机
					initCameraView();
					//初始化link
					initLinkView();
					break;
				case PIC_SOURCE_UPLOAD: 
					//trace("st:" + source_type);
					initUploadView();
					initLinkView();
					break;
			}
		
		}
		
		private function initUploadView():void
		{
			if (!contains(_upload_view))
			{
				addChild(_upload_view);
				_upload_view.addEventListener(UploadView.UPLOAD_VIEW_FINISHED_EVENT, onUploadViewFinished);
			}
			//填充相纸
			_upload_view.edit = edit_status;
			_upload_view.paper = Global.bg.xz;
			_upload_view.reset();
			if (!_link_view.visible)
			{
				_upload_view.visible = true;
			}
		
		}
		
		private function onUploadViewFinished(e:Event):void
		{
			_upload_view.visible = false;
			_link_view.visible = true;
			_link_view.photoBmd = _upload_view.photoBmd;
			_link_view.show();
		}
		
		private function initLinkView():void
		{
			if (!contains(_link_view))
			{
				_link_view.addEventListener(LinkView.LINK_VIEW_RETAKEPIC_EVENT, onReTake);
				_link_view.addEventListener(LinkView.LINK_VIEW_EDIT_EVENT, onEditPic);
				_link_view.visible = false;
				addChild(_link_view);
			}
		
		}
		
		private function onEditPic(e:Event):void
		{
			edit_status = true;
			onStart(e);
		}
		
		private function onReTake(e:Event):void
		{
			edit_status = false;
			onStart(e);
		}
		
		private function initCameraView():void
		{
			if (!contains(_camera_view))
			{
				//启动相机
				//trace("new camera");
				_mcamera = new MCamera();
				_mcamera.paper = Global.bg.xz;
				_mcamera.x = (stage.stageWidth - _mcamera.width) / 2;
				_mcamera.y = (stage.stageHeight - _mcamera.height) / 2 + 40;
				_mcamera.addEventListener(MCamera.TAKE_PIC_EVENT, onTakePic);
				_mcamera.addEventListener(MCamera.CAMERA_FAIL_EVENT, onCameraFail);
				_camera_view.addChild(_mcamera);
				addChild(_camera_view);
			}
			else
			{ //填充相纸
				_mcamera.paper = Global.bg.xz;
				_mcamera.reset();
				if (!_link_view.visible)
				{
					_camera_view.visible = true;
				}
			}
		
		}
		
		//摄像头启动失败
		private function onCameraFail(e:Event):void
		{
			
			if (contains(_camera_view))
			{
				_camera_view.visible = false;
				removeChild(_camera_view);
			}
			_upload_view.visible = true;
			source_type = PIC_SOURCE_UPLOAD;
			onStart(e);
		}
		
		//拍照
		private function onTakePic(e:Event):void
		{
			_mcamera.sleep();
			_camera_view.visible = false;
			_link_view.visible = true;
			_link_view.photoBmd = _mcamera.photoBmd;
			_link_view.show();
		}
	
	}

}
